﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using D2D2.Server.Networking;
using D2D2.SharedInterfaces.Networking;
using Lidgren.Network;
using Microsoft.Xna.Framework;

namespace D2D2.Server.Core
{
    public class ChestManagerServer
    {
        private long _chestCounter;
        private readonly ServerManager _serverManager;
        private readonly DropManagerServer _dropManager;
        private readonly Dictionary<long, List<ChestObject>> _chestHistory = new Dictionary<long, List<ChestObject>>();

        public ChestManagerServer(ServerManager serverManager, DropManagerServer dropManager)
        {
            _serverManager = serverManager;
            _dropManager = dropManager;

            Chests = new List<ChestObject>();
        }

        public List<ChestObject> Chests { get; private set; }
 
        public ChestObject AddChest(Vector2 location)
        {
            ChestObject chest = new ChestObject();
            long id = Interlocked.Increment(ref _chestCounter);

            chest.Id = id;
            chest.TotalVolume = 100;
            chest.CurrentVolume = 100;
            chest.ActionPerHit = 30;
            chest.VolumePerHit = 30;
            chest.HitTime = 0.4f;
            chest.Alive = true;

            chest.Location = location;

            Chests.Add(chest);

            List<ChestObject> historyList = new List<ChestObject>();
            _chestHistory.Add(chest.Id, historyList);

            return chest;
        }

        public void Update(float elapsed)
        {
            foreach (ChestObject chest in Chests)
            {
                bool needUpdate = chest.CalculateLive(elapsed);

                _serverManager.SendMessage(chest);

                chest.MessageTime = NetTime.Now;

                List<ChestObject> history = _chestHistory[chest.Id];
                history.Add(chest.Clone());
                if (history.Count > 30) history.RemoveAt(0);
            }
        }

        public void Hit(PlayerObject player, ChestObject chest)
        {
            int action = player.GetAction();
            
            if (action <= player.CurrentAction)
            {
                player.DecreaseAction(action);

                chest.Hit(player);
                _serverManager.SendMessage(player);

                List<int> curveNumbers = Drop.GetRandomDropCurves();

                _dropManager.Add(chest.Rectangle, curveNumbers[0]);
                _dropManager.Add(chest.Rectangle, curveNumbers[1]);
                _dropManager.Add(chest.Rectangle, curveNumbers[2]);
            }
        }
    }
}
